package com.ruoyi.merchant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.domain.MerchantApplication2;
import com.ruoyi.merchant.domain.MerchantAuditLog;
import com.ruoyi.merchant.domain.dto.MerchantAuditRequest;
import com.ruoyi.merchant.domain.vo.AuditHistoryVO;
import com.ruoyi.merchant.domain.vo.MerchantAuditDetailVO;
import com.ruoyi.merchant.domain.vo.MerchantAuditResponse;
import com.ruoyi.merchant.mapper.MerchantApplication2Mapper;
import com.ruoyi.merchant.mapper.MerchantAuditLogMapper;
import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.service.IMerchantAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MerchantAuditServiceImpl implements IMerchantAuditService {

    @Autowired
    private MerchantApplication2Mapper  merchantApplication2Mapper;
    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private MerchantAuditLogMapper auditLogMapper;

    /**
     * ⭐ 重构：查询待审核列表
     * 数据源改为 merchant_application 表
     */
    @Override
    public List<Merchant> selectAuditList(Merchant merchant) {
        MerchantApplication2 queryApp = new MerchantApplication2();

        // 1. 处理模糊查询条件
        queryApp.setMerchantName(merchant.getMerchantName());
        queryApp.setContactPhone(merchant.getContactPhone());

        // 2. ⭐ 关键修复：状态映射 (String -> Integer)
        // 前端传过来的是 externField1 (字符串)，我们需要转成 applicationStatus (数字)
        String statusStr = merchant.getExternField1();
        if (statusStr != null) {
            switch (statusStr) {
                case "UNDER_REVIEW":
                    queryApp.setApplicationStatus(0);
                    break;
                case "APPROVED":
                    queryApp.setApplicationStatus(1);
                    break;
                case "REJECTED":
                    queryApp.setApplicationStatus(2);
                    break;
                case "PENDING_INFO":
                    // 特殊情况：如果选"待完善"，申请表里可能没有记录，或者我们要查merchants表
                    // 这里暂时返回空，或者根据你的业务需求处理
                    // 通常"审核列表"只看已经提交申请的，所以 applicationStatus 不会对应 PENDING_INFO
                    return new ArrayList<>();
                default:
                    // 如果传了空字符串或全部，就不设状态条件，查询所有
                    break;
            }
        }

        // 3. 查询申请表
        List<MerchantApplication2> appList = merchantApplication2Mapper.selectAuditList(queryApp);

        // 4. 将 Application 对象转换为 Merchant 对象返回给前端
        return appList.stream().map(app -> {
            Merchant m = new Merchant();
            m.setMerchantId(app.getMerchantId());
            // 使用申请表里的新数据
            m.setMerchantName(app.getMerchantName());
            m.setContactPerson(app.getContactName());
            m.setContactPhone(app.getContactPhone());
            m.setAddress(app.getAddress());
            // 将数字状态转回字符串状态给前端显示
            m.setExternField1(convertStatusToString(app.getApplicationStatus()));
            m.setExternField2(app.getApplicationTime() != null ?
                    new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(app.getApplicationTime()) : "");
            m.setBusinessLicense(app.getBusinessLicense()); // 图片URL
            Merchant relatedMerchant = merchantMapper.selectMerchantById(app.getMerchantId());
            if (relatedMerchant != null) {
                m.setRating(relatedMerchant.getRating());
            } else {
                // 如果查不到商家（可能是数据脏了），给个默认值 0.00
                m.setRating(java.math.BigDecimal.ZERO);
            }
            return m;
        }).collect(Collectors.toList());
    }

    /**
     * ⭐ 重构：获取审核详情
     * 优先读取 merchant_application 表的数据
     */
    @Override
    public MerchantAuditDetailVO getAuditDetail(Long merchantId) {
        // 1. 查询最新的申请记录
        MerchantApplication2 application = merchantApplication2Mapper.selectLatestByMerchantId(merchantId);

        // 2. 查询商家基础信息 (用于获取 userId, rating 等申请表里没有的字段)
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);

        if (application == null) {
            // 如果没有申请记录，回退到显示商家表信息（或者是刚刚注册还没提交申请）
            if (merchant == null) {
                throw new ServiceException("商家信息不存在");
            }
            // 这里可以返回一个空的或者仅包含基础信息的VO，或者抛出异常提示未提交申请
            return buildDetailFromMerchant(merchant);
        }

        // 3. 查询审核历史
        List<MerchantAuditLog> auditLogs = auditLogMapper.selectAuditLogsByMerchantId(merchantId);
        List<AuditHistoryVO> auditHistory = auditLogs.stream().map(this::convertLogToVO).collect(Collectors.toList());

        // 4. ⭐ 构建详情VO，数据取自 Application
        MerchantAuditDetailVO detailVO = new MerchantAuditDetailVO();

        // 基础ID信息
        detailVO.setMerchantId(application.getMerchantId());
        detailVO.setUserId(merchant.getUserId()); // 取自商家表

        // ⭐ 业务数据：取自申请表（这是商家提交的最新数据）
        detailVO.setMerchantName(application.getMerchantName());
        detailVO.setContactPerson(application.getContactName());
        detailVO.setContactPhone(application.getContactPhone());
        detailVO.setAddress(application.getAddress());

        // 证照图片
        detailVO.setBusinessLicense(null); // 执照号字段如果申请表没存，可以留空
        detailVO.setBusinessLicenseImage(application.getBusinessLicense()); // 申请表存的是图片URL
        detailVO.setFoodLicense(null);
        // 如果申请表有存身份证/食品证，映射过来。这里假设映射到 foodLicenseImage 展示
        detailVO.setFoodLicenseImage(application.getIdCardFront());

        // 状态
        String auditStatusStr = convertStatusToString(application.getApplicationStatus());
        detailVO.setAuditStatus(auditStatusStr);
        detailVO.setAuditStatusText(getAuditStatusText(auditStatusStr));
        detailVO.setSubmitTime(application.getApplicationTime());

        // 其他信息
        detailVO.setRating(merchant.getRating()); // 评分取自商家表
        detailVO.setAuditHistory(auditHistory);

        return detailVO;
    }
    // 辅助方法：状态转换 int -> string
    private String convertStatusToString(Integer status) {
        if (status == null) return "PENDING_INFO";
        switch (status) {
            case 0: return "UNDER_REVIEW";
            case 1: return "APPROVED";
            case 2: return "REJECTED";
            default: return "UNKNOWN";
        }
    }

    /**
     * 辅助方法：兜底逻辑，仅从商家表构建详情
     * (用于刚注册未提交申请，或申请记录缺失的情况)
     */
    private MerchantAuditDetailVO buildDetailFromMerchant(Merchant merchant) {
        MerchantAuditDetailVO vo = new MerchantAuditDetailVO();

        // 1. 基础身份信息
        vo.setMerchantId(merchant.getMerchantId());
        vo.setUserId(merchant.getUserId());

        // 2. 业务基本信息
        vo.setMerchantName(merchant.getMerchantName());
        vo.setContactPerson(merchant.getContactPerson());
        vo.setContactPhone(merchant.getContactPhone());
        vo.setAvatarUrl(merchant.getAvatarUrl());
        vo.setAddress(merchant.getAddress());

        // 3. 位置信息
        vo.setLatitude(merchant.getLatitude());
        vo.setLongitude(merchant.getLongitude());

        // 4. 证照号码 (注意：商家表里存的是号码，图片URL通常在申请表里)
        vo.setBusinessLicense(merchant.getBusinessLicense());
        vo.setFoodLicense(merchant.getFoodLicense());

        // 这里的图片只能置空，因为商家主表没有专门存图片URL的字段(除非你扩展了字段)
        vo.setBusinessLicenseImage(null);
        vo.setFoodLicenseImage(null);

        // 5. 审核状态处理
        String auditStatus = StringUtils.defaultIfBlank(merchant.getExternField1(), "PENDING_INFO");
        vo.setAuditStatus(auditStatus);
        vo.setAuditStatusText(getAuditStatusText(auditStatus));

        // 6. 尝试获取提交时间
        // 约定：在 UNDER_REVIEW 状态下，externField2 存储的是提交时间字符串
        if ("UNDER_REVIEW".equals(auditStatus) && StringUtils.isNotEmpty(merchant.getExternField2())) {
            try {
                vo.setSubmitTime(DateUtils.parseDate(merchant.getExternField2()));
            } catch (Exception e) {
                // 解析失败忽略，避免影响主流程
            }
        }

        // 7. 其他统计信息
        vo.setStatus(merchant.getStatus()); // 营业状态
        vo.setRating(merchant.getRating());
        vo.setCreatedAt(merchant.getCreateTime());
        vo.setUpdatedAt(merchant.getUpdateTime());

        // 8. 审核历史置空
        vo.setAuditHistory(new ArrayList<>());

        return vo;
    }

    // 辅助方法：转换日志
    private AuditHistoryVO convertLogToVO(MerchantAuditLog log) {
        AuditHistoryVO vo = new AuditHistoryVO();
        vo.setAuditTime(log.getAuditTime());
        vo.setAuditStatus(log.getAuditStatus());
        vo.setAuditRemark(log.getAuditRemark());
        vo.setAuditorName(log.getAuditorName());
        return vo;
    }


    /**
     * 处理商家审核
     * @param request 审核请求
     * @param auditorId 审核人ID
     * @param auditorName 审核人姓名
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MerchantAuditResponse processAudit(MerchantAuditRequest request,
                                              Long auditorId,
                                              String auditorName) {
        // 1. 参数校验
        request.validate();

        // 2. 查询商家信息
        Merchant merchant = merchantMapper.selectMerchantById(request.getMerchantId());
        if (merchant == null) {
            throw new ServiceException("商家信息不存在");
        }

        // 3. 查询最新的申请记录
        MerchantApplication2 application =
                merchantApplication2Mapper.selectLatestByMerchantId(request.getMerchantId());
        if (application == null) {
            throw new ServiceException("未找到该商家的申请记录");
        }

        // 4. 校验当前状态（只有待审核的才能审核）
        String currentStatus = StringUtils.defaultIfBlank(
                merchant.getExternField1(), "PENDING_INFO");

        if (!"UNDER_REVIEW".equals(currentStatus)) {
            throw new ServiceException("当前商家状态不是审核中，无法审核");
        }

        if (application.getApplicationStatus() != 0) {
            throw new ServiceException("该申请已被处理，无法重复审核");
        }

        // 5. ⭐ 审核通过：同步申请数据到商家表
        if ("APPROVED".equals(request.getAuditStatus())) {
            syncApplicationToMerchant(application, merchant);
        }

        // 6. 更新商家表的审核状态
        Merchant updateMerchant = new Merchant();
        updateMerchant.setMerchantId(request.getMerchantId());
        updateMerchant.setExternField1(request.getAuditStatus());
        updateMerchant.setExternField2(null);

        // 如果拒绝，将拒绝原因存储到 extern_field2
        if ("REJECTED".equals(request.getAuditStatus())) {
            updateMerchant.setExternField2(request.getAuditRemark());
        }

        int rows = merchantMapper.updateMerchant(updateMerchant);
        if (rows <= 0) {
            throw new ServiceException("更新商家状态失败");
        }

        // 7. 更新申请表的审核状态
        MerchantApplication2 updateApplication = new MerchantApplication2();
        updateApplication.setApplicationId(application.getApplicationId());

        if ("APPROVED".equals(request.getAuditStatus())) {
            updateApplication.setApplicationStatus(1); // 审核通过
        } else {
            updateApplication.setApplicationStatus(2); // 审核驳回
            updateApplication.setRejectReason(request.getAuditRemark());
        }

        merchantApplication2Mapper.updateApplicationStatus2(updateApplication);

        // 8. 记录审核日志
        MerchantAuditLog auditLog = new MerchantAuditLog();
        auditLog.setMerchantId(request.getMerchantId());
        auditLog.setAuditType("SETTLEMENT");
        auditLog.setAuditStatus(request.getAuditStatus());
        auditLog.setAuditRemark(request.getAuditRemark());
        auditLog.setAuditorId(auditorId);
        auditLog.setAuditorName(auditorName);
        auditLog.setAuditTime(new Date());

        // 保存申请数据快照
        auditLog.setSubmitData(JSON.toJSONString(application));

        auditLogMapper.insertAuditLog(auditLog);

        // 10. 返回结果
        return MerchantAuditResponse.builder()
                .merchantId(request.getMerchantId())
                .auditStatus(request.getAuditStatus())
                .auditTime(new Date())
                .build();
    }

    /**
     * ⭐ 将申请数据同步到商家表（审核通过时调用）
     */
    private void syncApplicationToMerchant(MerchantApplication2 application, Merchant merchant) {
        Merchant updateMerchant = new Merchant();
        updateMerchant.setMerchantId(merchant.getMerchantId());

        // 同步申请表中的数据到商家表
        updateMerchant.setMerchantName(application.getMerchantName());
        updateMerchant.setContactPerson(application.getContactName());
        updateMerchant.setAddress(application.getAddress());
        updateMerchant.setBusinessLicense(application.getBusinessLicense());

        // 如果申请表中有食品许可证，也同步（如果你的申请表没有这个字段，就不同步）
        // updateMerchant.setFoodLicense(application.getFoodLicense());

        // 设置默认经纬度（如果申请表没有经纬度）
        // 实际项目中应该根据地址解析经纬度
        if (updateMerchant.getLatitude() == null) {
            updateMerchant.setLatitude(new java.math.BigDecimal("0"));
        }
        if (updateMerchant.getLongitude() == null) {
            updateMerchant.setLongitude(new java.math.BigDecimal("0"));
        }

        // 审核通过后，状态保持休息（1），需要商家主动开业
        updateMerchant.setStatus(1);

        int rows = merchantMapper.updateMerchant(updateMerchant);
        if (rows <= 0) {
            throw new ServiceException("同步数据到商家表失败");
        }
    }

    /**
     * 更新商家申请表的审核状态
     * @param request 审核请求
     * @return 更新影响的行数
     */
    private int updateMerchantApplicationStatus(MerchantAuditRequest request) {
        // 构建更新对象
        MerchantApplication2 updateApplication = new MerchantApplication2();
        updateApplication.setMerchantId(request.getMerchantId());

        // 根据审核状态设置对应的申请状态
        if ("APPROVED".equals(request.getAuditStatus())) {
            // 审核通过
            updateApplication.setApplicationStatus(1); // 1表示审核通过
        } else if ("REJECTED".equals(request.getAuditStatus())) {
            // 审核驳回
            updateApplication.setApplicationStatus(2); // 2表示审核驳回
            updateApplication.setRejectReason(request.getAuditRemark());
        } else {
            // 其他状态，这里可以根据需要处理
            updateApplication.setApplicationStatus(0); // 0或其他默认状态
        }

        // 执行更新操作
        return merchantApplication2Mapper.updateByMerchantId(updateApplication);
    }

    /**
     * ⭐ 重构：获取审核统计 (保证与列表数据源一致)
     */
    @Override
    public Map<String, Integer> getAuditStatistics() {
        Map<String, Integer> statistics = new HashMap<>();

        // 1. 待审核 (状态 0) - 查 merchant_application
        statistics.put("UNDER_REVIEW", merchantApplication2Mapper.countByStatus(0));

        // 2. 已通过 (状态 1) - 查 merchant_application
        statistics.put("APPROVED", merchantApplication2Mapper.countByStatus(1));

        // 3. 已拒绝 (状态 2) - 查 merchant_application
        statistics.put("REJECTED", merchantApplication2Mapper.countByStatus(2));

        // 4. 待完善 (PENDING_INFO)
        // 特殊情况：申请表中没有"待完善"的记录，因为只有提交了才会进申请表。
        // 这个数据必须查 merchants 表，条件是 extern_field1 = 'PENDING_INFO'
        // 或者我们可以认为在"审核管理"里不需要关注"待完善"的商家，填0也可以。
        // 这里保留查询 merchants 表以显示注册了但没提交的人数：
        statistics.put("PENDING_INFO", merchantMapper.countByAuditStatus("PENDING_INFO"));

        return statistics;
    }

    private String getAuditStatusText(String auditStatus) {
        Map<String, String> statusMap = new HashMap<>();
        statusMap.put("PENDING_INFO", "待完善信息");
        statusMap.put("UNDER_REVIEW", "审核中");
        statusMap.put("APPROVED", "已通过");
        statusMap.put("REJECTED", "已拒绝");
        return statusMap.getOrDefault(auditStatus, "未知状态");
    }
}
